package b1.mobile.blackberry.io.xml;

import org.json.me.JSONArray;
import org.json.me.JSONException;
import org.json.me.JSONObject;
import org.xml.sax.Attributes;
import org.xml.sax.helpers.DefaultHandler;

public class SoapParserHandler extends DefaultHandler {
	String desiredTag = "";
	StringBuffer desiredTagContent = new StringBuffer();
	boolean isMeet = false;
	
	public SoapParserHandler(String tag){
		this.desiredTag = tag;
	}
	
	public void startElement(String uri, String localName, String qName, Attributes attributes){
		if(localName.equals(this.desiredTag)){
			isMeet = true;
		}
	}
	
	public void characters(char[] ch, int start, int length){
		if(isMeet){
			desiredTagContent.append(ch, start, length);
		}
	}
	
	public void endElement(String uri, String localName, String qName){
		if(localName.equals(this.desiredTag)){
			isMeet = false;
		}
	}
	
	public String getContent(){
		return desiredTagContent.toString();
	}
	
	public Object getJson(){
		String jsonStr = this.getContent().trim();
		Object retVal = jsonStr;
		try {
			if(jsonStr.startsWith("{")){
				JSONObject jsonObj = new JSONObject(jsonStr);
				retVal = jsonObj;
			} else if(jsonStr.startsWith("[")){
				JSONArray jsonArray = new JSONArray(jsonStr);
				retVal = jsonArray;
			} else {
				
			}
		} catch (JSONException e) {
			System.out.println(e.getMessage());
		}
		return retVal;
	}
}
